package info.sgu.ttdt;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import info.androidhive.slidingmenu.R;
import info.sgu.ttdt.adapter.DatabaseHelper;
import info.sgu.ttdt.adapter.JsonUrl;
import info.sgu.ttdt.model.BookMark;
import info.sgu.ttdt.model.HocKy;
import info.sgu.ttdt.model.TaiKhoan;
import info.sgu.ttdt.model.ThoiKhoaBieu;
import info.sgu.ttdt.model.Tuan;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import android.widget.AdapterView.OnItemSelectedListener;

public class ThoiKhoaBieuFragment extends ListFragment {

	private ProgressDialog pDialog;

	// URL to get contacts JSON
	private static String url;

	// JSON Node names
	private static final String tag_mamonhoc = "mamonhoc";
	private static final String tag_tenmonhoc = "tenmonhoc";
	private static final String tag_phonghoc = "phonghoc";
	private static final String tag_thu = "thu";
	private static final String tag_tietbatdau = "tietbatdau";
	private static final String tag_sotiet = "sotiet";
	private static final String tag_giangvien = "giangvien";
	private static final String tag_lop = "lop";

	private static final String tag_matuan = "matuan";
	private static final String tag_tenhocky = "tenhocky";
	
	private static final String tag_masinhvien = "masinhvien";
	private static final String tag_tensinhvien = "tensinhvien";
	private static final String tag_nganh = "nganh";
	private static final String tag_khoa = "khoa";
	private static final String tag_hedaotao = "hedaotao";
	private static final String tag_khoahoc = "khoahoc";

	Spinner spinner1;
	Spinner spinner2;
	Spinner spinner_masv;
	Spinner spinner_thu;
	List<String> str;
	List<String> str2;
	String[] thu_list = {"Thứ Hai", "Thứ Ba", "Thứ Tư", "Thứ Năm", "Thứ Sáu", "Thứ Bảy", "Chủ nhật"};
	List<String> str_masv;

	DatabaseHelper db;
	List<ThoiKhoaBieu> datalist;

	// contacts JSONArray
	JSONArray data = null;
	ViewSwitcher viewSwitcher;

	// Hashmap for ListView
	ArrayList<HashMap<String, String>> dataList;

	Button btn_view;
	ImageButton btn_reload;
	ImageButton btn_bookmark;
	EditText txt_masv;;
	TextView txt_name;
	String masinhvien;
	String name;
	boolean set = true;

	public ThoiKhoaBieuFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_thoikhoabieu,
				container, false);
		SharedPreferences settings = getActivity()
				.getSharedPreferences("UserInfo", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("type", 2);
		editor.commit();
		db = new DatabaseHelper(getActivity());
		datalist = new ArrayList<ThoiKhoaBieu>();
		dataList = new ArrayList<HashMap<String, String>>();
		str = new ArrayList<String>();
		str2 = new ArrayList<String>();
		str_masv = new ArrayList<String>();
		spinner1 = (Spinner) rootView.findViewById(R.id.spinner2);
		spinner2 = (Spinner) rootView.findViewById(R.id.spinner3);
		spinner_masv = (Spinner) rootView.findViewById(R.id.spinner_masv);
		spinner_thu = (Spinner) rootView.findViewById(R.id.spinner_thu);
		ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(
				getActivity(), android.R.layout.simple_spinner_item, thu_list);
		spinner_thu.setAdapter(adapter_state);

		viewSwitcher = (ViewSwitcher) rootView.findViewById(R.id.viewSwitcher3);
		txt_masv = (EditText) rootView.findViewById(R.id.editText_masv);
		txt_name = (TextView) rootView.findViewById(R.id.textView_name);

		OnItemSelectedListener SelectedListener = new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> spinner, View container,
					int position, long id) {
				Load(position, spinner1.getSelectedItemPosition(), spinner_thu.getSelectedItemPosition()+2+"");

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		};
		spinner2.setOnItemSelectedListener(SelectedListener);
		OnItemSelectedListener SelectedListener2 = new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> spinner, View container,
					int position, long id) {
				List<Tuan> ts = db.getTuans(masinhvien, position);
				str2.clear();
				for (Tuan t : ts) {
					str2.add(t.getTentuan());
				}
				ArrayAdapter<String> adapter_state2 = new ArrayAdapter<String>(
						getActivity(), android.R.layout.simple_spinner_item,
						str2);
				spinner2.setAdapter(adapter_state2);
				if (!db.checkTuan(masinhvien, position)) {
					Load(-1, position, "2");
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		};
		spinner1.setOnItemSelectedListener(SelectedListener2);

		OnItemSelectedListener SelectedListener_thu = new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> spinner, View container,
					int position, long id) {
				Load(spinner2.getSelectedItemPosition(), spinner1.getSelectedItemPosition(), position+2+"");
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		};
		spinner_thu.setOnItemSelectedListener(SelectedListener_thu);
		
		OnItemSelectedListener SelectedListener_masv = new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> spinner, View container,
					int position, long id) {
				masinhvien = (String)spinner.getSelectedItem();
				url = JsonUrl.getUrlThoiKhoaBieu(masinhvien);
				if (db.checkThoiKhoaBieu(masinhvien)) {
					if (db.checkTaiKhoan(masinhvien)) {
						TaiKhoan tk = db.getTaiKhoan(masinhvien);
						name = tk.getTensinhvien();
					}
					Load2(0, 0, "2");
				} else {
					// Calling async task to get json
					new GetContacts().execute();
				}
				CurrentDate();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		};
		spinner_masv.setOnItemSelectedListener(SelectedListener_masv);
		
		btn_view = (Button) rootView.findViewById(R.id.button_view);
		btn_view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				masinhvien = txt_masv.getText().toString();
				url = JsonUrl.getUrlThoiKhoaBieu(masinhvien);
				viewSwitcher.showNext();
				if (db.checkThoiKhoaBieu(masinhvien)) {
					if (db.checkTaiKhoan(masinhvien)) {
						TaiKhoan tk = db.getTaiKhoan(masinhvien);
						name = tk.getTensinhvien();
					}
					Load2(0, 0, "2");
				} else {
					// Calling async task to get json
					new GetContacts().execute();
				}
				CurrentDate();
			}
		});
		btn_reload = (ImageButton) rootView.findViewById(R.id.button_reload2);
		btn_reload.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				url = JsonUrl.getUrlThoiKhoaBieu(masinhvien);
				str.clear();
				str2.clear();
				// Calling async task to get json
				new GetContacts().execute();
				CurrentDate();
			}
		});

		btn_bookmark = (ImageButton) rootView.findViewById(R.id.imageButton1);
		btn_bookmark.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!db.checkBookmark(masinhvien, "Thời khóa biểu"))
				{
					BookMark bm = new BookMark(masinhvien, name, "Thời khóa biểu");
					db.createBookmark(bm);
					Toast.makeText(getActivity(), "Lưu Bookmark thành công", Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(getActivity(), "Bookmark đã tồn tại", Toast.LENGTH_SHORT).show();
			}
		});
		
		//SharedPreferences settings = getActivity().getSharedPreferences("UserInfo", 0);
		String masv = settings.getString("masinhvien", "").toString();
		if (!masv.equals("null") && !masv.isEmpty()) {
			masinhvien = settings.getString("masinhvien", "").toString();
			name = settings.getString("tensinhvien", "").toString();
			url = JsonUrl.getUrlThoiKhoaBieu(masinhvien);
			viewSwitcher.showNext();
			if (db.checkThoiKhoaBieu(masinhvien)) {
				Load2(0, 0, "2");
			} else {
				// Calling async task to get json
				new GetContacts().execute();
			}
			CurrentDate();
			
		}

		return rootView;
	}

	private class GetContacts extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Showing progress dialog
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Vui lòng chờ...");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();

			// Making a request to url and getting response
			if(!db.checkTaiKhoan(masinhvien))
			{
				String url2 = JsonUrl.getUrlTaiKhoan(masinhvien);
				String jsonStr2 = sh.makeServiceCall(url2, ServiceHandler.GET);
				Log.d("Response: ", "> " + jsonStr2);
	
				if (jsonStr2 != null) {
					try {
						JSONObject jsonObj = new JSONObject(jsonStr2);
						JSONObject c = jsonObj.getJSONObject("taikhoan");
						if (c != null) {
							String masinhvien = c.getString(tag_masinhvien);
							String tensinhvien = c.getString(tag_tensinhvien);
							String lop = c.getString(tag_lop);
							String nganh = c.getString(tag_nganh);
							String khoa = c.getString(tag_khoa);
							String hedaotao = c.getString(tag_hedaotao);
							String khoahoc = c.getString(tag_khoahoc);
	
							TaiKhoan tk = new TaiKhoan(masinhvien, tensinhvien,
									lop, nganh, khoa, hedaotao, khoahoc, "");
							db.createTaiKhoan(tk);
						}
						
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					Log.e("ServiceHandler", "Couldn't get any data from the url");
				}
			}
			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null && !jsonStr.equals("-1")) {
				try {
					JSONObject jsonObj = new JSONObject(jsonStr);
					JSONObject c4 = jsonObj.getJSONObject("taikhoan");
					name = c4.getString("tensinhvien");
					// Getting JSON Array node
					JSONArray data2 = jsonObj.getJSONArray("hocky");
					if (data2.length() > 0) {
						db.deleteThoiKhoaBieu(masinhvien);
						db.deleteHocKy(masinhvien, "tkb");
						db.deleteTuan(masinhvien);
					}
					for (int j = 0; j < data2.length(); j++) {
						JSONObject c2 = data2.getJSONObject(j);
						if (!c2.getString("tuan").equals("null")) {
							data = c2.getJSONArray("tuan");
							for (int k = 0; k < data.length(); k++) {
								JSONObject c1 = data.getJSONObject(k);
								String tentuan = c1.getString(tag_matuan);
								Tuan t = new Tuan(tentuan);
								db.createTuan(t, masinhvien, j);

								if (!c1.getString("monhoc").equals("null")) {

									JSONArray data1 = c1.getJSONArray("monhoc");
									// looping through All Contacts
									for (int i = 0; i < data1.length(); i++) {
										JSONObject c = data1.getJSONObject(i);

										String mamonhoc = c
												.getString(tag_mamonhoc);
										String tenmonhoc = c
												.getString(tag_tenmonhoc);
										String phonghoc = c
												.getString(tag_phonghoc);
										String thu = c.getString(tag_thu);
										String tietbatdau = c
												.getString(tag_tietbatdau);
										String sotiet = c.getString(tag_sotiet);
										String giangvien = c
												.getString(tag_giangvien);
										String lop = c.getString(tag_lop);
										ThoiKhoaBieu tkb = new ThoiKhoaBieu(
												mamonhoc, tenmonhoc, phonghoc,
												thu, tietbatdau, sotiet,
												giangvien, lop);
										db.createThoiKhoaBieu(tkb, k, j,
												masinhvien);
									}

								}
							}
						}
						String tenhocky = c2.getString(tag_tenhocky);
						HocKy hk = new HocKy(tenhocky);
						db.createHocKy(hk, masinhvien, "tkb");

					}
					dataList.clear();
					datalist = db.getAllThoiKhoaBieus(0, 0, masinhvien, "2");
					for (ThoiKhoaBieu c : datalist) {
						HashMap<String, String> data = new HashMap<String, String>();
						data.put(tag_mamonhoc, "Mã môn học: " + c.getMamonhoc());
						data.put(tag_tenmonhoc,
								"Tên môn học: " + c.getTenmonhoc());
						data.put(tag_phonghoc, "Phòng học: " + c.getPhonghoc());
						data.put(tag_thu, "Thứ: " + c.getThu());
						data.put(tag_tietbatdau,
								"Tiết bắt đầu: " + c.getTietbatdau());
						data.put(tag_sotiet, "Số tiết: " + c.getSotiet());
						data.put(tag_giangvien,
								"Giảng viên: " + c.getGiangvien());
						data.put(tag_lop, "Lớp: " + c.getLop());
						// adding contact to contact list
						dataList.add(data);
						// Log.w("abc", c.getTenmonhoc());
					}

					List<HocKy> hks = db.getHocKys(masinhvien, "tkb");
					for (HocKy hk : hks) {
						str.add(hk.getTenhocky());
						// Log.w("abc", hk.getTenhocky() + "456");
					}
					if (db.checkTuan(masinhvien, 0)) {
						List<Tuan> ts = db.getTuans(masinhvien, 0);
						for (Tuan t : ts) {
							str2.add(t.getTentuan());
							Log.w("abc", t.getTentuan() + "456");
						}
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Dismiss the progress dialog
			if (pDialog.isShowing())
				pDialog.dismiss();
			/**
			 * Updating parsed JSON data into ListView
			 * */

			ListAdapter adapter = new SimpleAdapter(getActivity(), dataList,
					R.layout.list_item4,
					new String[] { tag_mamonhoc, tag_tenmonhoc, tag_phonghoc,
							tag_thu, tag_tietbatdau, tag_sotiet, tag_giangvien,
							tag_lop }, new int[] { R.id.text1, R.id.text2,
							R.id.text3, R.id.text4, R.id.text5, R.id.text6,
							R.id.text7, R.id.text8 });
			setListAdapter(adapter);

			ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(
					getActivity(), android.R.layout.simple_spinner_item, str);
			spinner1.setAdapter(adapter_state);

			if(set)
			{
				str_masv.clear();
				List<TaiKhoan> tks = db.getAllTaiKhoans();
				int count = 0;
				int position = 0;
				for (TaiKhoan tk : tks)
				{
					if(masinhvien.equals(tk.getMasinhvien()))
						position = count;
					str_masv.add(tk.getMasinhvien());
					count++;
				}
				ArrayAdapter<String> adapter_state3 = new ArrayAdapter<String>(
						getActivity(), android.R.layout.simple_spinner_item, str_masv);
				spinner_masv.setAdapter(adapter_state3);
				spinner_masv.setSelection(position);
				set = false;
			}
			TaiKhoan ttk = db.getTaiKhoan(masinhvien);
			name = ttk.getTensinhvien();
			txt_name.setText(masinhvien + " - " + name);
			int num = db.numberTaiKhoan();
			((MainActivity)getActivity()).NumberAccount(num, 2);
		}

	}

	private void Load(int tuanid, int hockyid, String thu) {
		dataList.clear();
		datalist = db.getAllThoiKhoaBieus(tuanid, hockyid, masinhvien, thu);
		for (ThoiKhoaBieu c : datalist) {
			HashMap<String, String> data = new HashMap<String, String>();
			data.put(tag_mamonhoc, "Mã môn học: " + c.getMamonhoc());
			data.put(tag_tenmonhoc, "Tên môn học: " + c.getTenmonhoc());
			data.put(tag_phonghoc, "Phòng học: " + c.getPhonghoc());
			data.put(tag_thu, "Thứ: " + c.getThu());
			data.put(tag_tietbatdau, "Tiết bắt đầu: " + c.getTietbatdau());
			data.put(tag_sotiet, "Số tiết: " + c.getSotiet());
			data.put(tag_giangvien, "Giảng viên: " + c.getGiangvien());
			data.put(tag_lop, "Lớp: " + c.getLop());
			// adding contact to contact list
			dataList.add(data);
		}

		ListAdapter adapter = new SimpleAdapter(getActivity(), dataList,
				R.layout.list_item4, new String[] { tag_mamonhoc,
						tag_tenmonhoc, tag_phonghoc, tag_thu, tag_tietbatdau,
						tag_sotiet, tag_giangvien, tag_lop }, new int[] {
						R.id.text1, R.id.text2, R.id.text3, R.id.text4,
						R.id.text5, R.id.text6, R.id.text7, R.id.text8 });
		setListAdapter(adapter);
		//CurrentDate();
	}

	private void Load2(int tuanid, int hockyid, String thu) {
		dataList.clear();
		datalist = db.getAllThoiKhoaBieus(tuanid, hockyid, masinhvien, thu);
		for (ThoiKhoaBieu c : datalist) {
			HashMap<String, String> data = new HashMap<String, String>();
			data.put(tag_mamonhoc, "Mã môn học: " + c.getMamonhoc());
			data.put(tag_tenmonhoc, "Tên môn học: " + c.getTenmonhoc());
			data.put(tag_phonghoc, "Phòng học: " + c.getPhonghoc());
			data.put(tag_thu, "Thứ: " + c.getThu());
			data.put(tag_tietbatdau, "Tiết bắt đầu: " + c.getTietbatdau());
			data.put(tag_sotiet, "Số tiết: " + c.getSotiet());
			data.put(tag_giangvien, "Giảng viên: " + c.getGiangvien());
			data.put(tag_lop, "Lớp: " + c.getLop());
			// adding contact to contact list
			dataList.add(data);
		}
		str.clear();
		List<HocKy> hks = db.getHocKys(masinhvien, "tkb");
		for (HocKy hk : hks) {
			str.add(hk.getTenhocky());
		}
		str2.clear();
		List<Tuan> ts = db.getTuans(masinhvien, 0);
		for (Tuan t : ts) {
			str2.add(t.getTentuan());
		}

		ListAdapter adapter = new SimpleAdapter(getActivity(), dataList,
				R.layout.list_item4, new String[] { tag_mamonhoc,
						tag_tenmonhoc, tag_phonghoc, tag_thu, tag_tietbatdau,
						tag_sotiet, tag_giangvien, tag_lop }, new int[] {
						R.id.text1, R.id.text2, R.id.text3, R.id.text4,
						R.id.text5, R.id.text6, R.id.text7, R.id.text8 });
		setListAdapter(adapter);

		ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(
				getActivity(), android.R.layout.simple_spinner_item, str);
		spinner1.setAdapter(adapter_state);

		ArrayAdapter<String> adapter_state2 = new ArrayAdapter<String>(
				getActivity(), android.R.layout.simple_spinner_item, str2);
		spinner2.setAdapter(adapter_state2);
		
		if(set)
		{
			str_masv.clear();
			List<TaiKhoan> tks = db.getAllTaiKhoans();
			int count = 0;
			int position = 0;
			for (TaiKhoan tk : tks)
			{
				if(masinhvien.equals(tk.getMasinhvien()))
					position = count;
				str_masv.add(tk.getMasinhvien());
				count++;
			}
			ArrayAdapter<String> adapter_state3 = new ArrayAdapter<String>(
					getActivity(), android.R.layout.simple_spinner_item, str_masv);
			spinner_masv.setAdapter(adapter_state3);
			spinner_masv.setSelection(position);
			set = false;
		}
		txt_name.setText(masinhvien + " - " + name);
		//CurrentDate();
	}
	
	protected void CurrentDate()
	{
		int position = 0;
		int position2 = 0;
		Date currentDate = new Date();
		SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
		for(String s : str2)
		{
			String start = s.substring(s.length()-29, s.length()-19);
			String end = s.substring(s.length()-11, s.length()-1);
			Date startDate = new Date();
			Date endDate = new Date();
			
			try {
				//currentDate = df.parse("27/08/2014");
				startDate = df.parse(start);
				endDate = df.parse(end);
				Log.w("abc", currentDate + " - " + startDate + " - " +endDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(currentDate.compareTo(startDate)<0)
	        {
				break;
	        }
	        else 
	        {
				if(currentDate.compareTo(endDate)<=0)
		        {
					break;
		        }
	        }
			position++;

		}
		if(position>str2.size()-1)
			position = str2.size()-1;
		spinner2.setSelection(position);
		SimpleDateFormat sdf = new SimpleDateFormat("EEE");
		String dayOfTheWeek = sdf.format(currentDate);
		if(dayOfTheWeek.equals("Mon"))
			position2 = 0;
		else if(dayOfTheWeek.equals("Tue"))
			position2 = 1;
		else if(dayOfTheWeek.equals("Wed"))
			position2 = 2;
		else if(dayOfTheWeek.equals("Thu"))
			position2 = 3;
		else if(dayOfTheWeek.equals("Fri"))
			position2 = 4;
		else if(dayOfTheWeek.equals("Sat"))
			position2 = 5;
		else if(dayOfTheWeek.equals("Sun"))
			position2 = 6;
		spinner_thu.setSelection(position2);
	}

}
